package com.azunitech.apm.bundles.android;

import java.util.Enumeration;
import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.azunitech.apm.bundles.android.receivers.LocationEventReceiver;
import com.azunitech.apm.messages.Actions;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.widget.Toast;

/*
 * This Bundle can be a bridge for OSGi and Android Context
 */
public class Activator implements BundleActivator {
	private static final Logger log = LoggerFactory.getLogger(Activator.class);
    private BundleContext m_BundleContext;  
	static Context m_Context;
	private BroadcastReceiver m_LocationChangedReceiver;	
	private Hashtable<String, BroadcastReceiver> m_ReceiverList = new Hashtable<String, BroadcastReceiver>();
	
	//This is used to track the Context Service
	private ServiceTracker<Context,Context> m_ServiceTracker;	
    public void start(BundleContext bc) {
    	log.debug("Android Bundle start");
    	m_BundleContext = bc;    	
        m_ServiceTracker = new ServiceTracker<Context,Context>(bc, android.content.Context.class.getName(), new Customizer());  
        m_ServiceTracker.open();  
    }

    /**
     * Unregister all receivers and clean the receiver list for performance and memory
     */
    public void stop(BundleContext context) {
       	log.debug("Android Bundle start");
    	Enumeration<String> enumKey = m_ReceiverList.keys();
    	while(enumKey.hasMoreElements()){
    		String receiverName = enumKey.nextElement();
    		BroadcastReceiver receiver = m_ReceiverList.get(receiverName);
    		m_Context.unregisterReceiver(receiver);
    		log.debug("Register receiver " + receiverName + " to android context.");
    	}
    	this.m_ReceiverList.clear();
    }
    
    /**
     * make calls to the UI thread 
     * @param context
     * @param runnable
     */
    public static void runOnContext(Context context, Runnable runnable) {
        Handler handler = new Handler(context.getMainLooper());
        handler.post(runnable);
    }
    
    /*
     * As Echo Service is depended on the preference services, so when the Preference Service is available
     * we register the Echo Service
     */
    // customizer that handles tracked service registration/modification/unregistration events  
    private class Customizer implements ServiceTrackerCustomizer<Context,Context> {  
    	
        public Context addingService(ServiceReference<Context> reference) {  
            System.out.println("Android context is added to OSGi");  
          	
    		log.debug("found the Andorid Context in OSGi Services");
    		m_Context = (Application) m_BundleContext.getService(reference);
     		
    		//Register all event receiver, so we can get events from android side
    		IntentFilter filter = new IntentFilter(Actions.ACTION_LOCATION_CHANGED);
    		m_LocationChangedReceiver = new LocationEventReceiver();
    		m_Context.registerReceiver(m_LocationChangedReceiver, filter);
    		m_ReceiverList.put(Actions.ACTION_LOCATION_CHANGED, m_LocationChangedReceiver);
    		
    		
    		log.debug("Register receiver " + Actions.ACTION_LOCATION_CHANGED + " to android context.");

    		//Notice android application for the android context service
    		runOnContext(m_Context, new Runnable() {
    			public void run() {
    				Toast.makeText(m_Context, "Found Android as Services in OSGi", Toast.LENGTH_LONG).show();
    			}
    		});
            return m_Context;
        }  
 
		public void modifiedService(ServiceReference<Context> reference, Context service) {
	       	//Because the Android context is added from the OSGI Felix framework, so it will not be updated
		}
	
		public void removedService(ServiceReference<Context> reference,
				Context service) {
        	//Because the Android context is added from the OSGI Felix framework, so it will not be removed
		}
    }  
}